<?php
require_once (dirname(__FILE__) . '/../forms/Login.php');
require_once (dirname(__FILE__) . '/../forms/Forget.php');
require_once (dirname(__FILE__) . '/../forms/Signup.php');
class Default_AuthController extends Zend_Controller_Action
{
	public function preDispatch()
    {
        if (Zend_Auth::getInstance()->hasIdentity()) {
            // If the user is logged in, we don't want to show the login form;
            // however, the logout action should still be available
            if ('logout' != $this->getRequest()->getActionName()) {
                $this->_redirect('/');
            }
        } else {
            // If they aren't, they can't logout, so that action should 
            // redirect to the login form
            if ('logout' == $this->getRequest()->getActionName()) {
                $this->_redirect('/auth/login');
            }
		}
    }

    protected function _getAuthAdapter($email, $password)
    {
        $authAdapter = new Common_Doctrine_Auth_Adapter(Doctrine::getConnectionByTableName('Default_Model_User'));
 
        $encryptedPassword = md5($password);
 
        $authAdapter->setTableName('Default_Model_User u')
            ->setIdentityColumn('u.email')
            ->setCredentialColumn('u.password')
            ->setIdentity($email)
            ->setCredential($encryptedPassword);
 
        return $authAdapter;
    }
	
    public function init()
    {
        if ($this->getRequest()->isXmlHttpRequest()) {
            $this->_helper->layout->disableLayout();
		}
    }

    public function indexAction()
    {
        $this->_redirect('/auth/login');
    }

    public function loginAction()
    {
        if (isset($_SESSION['Zend_Auth'])){
    		$storage = new Zend_Auth_Storage_Session();
        	$storage->clear();
    	}
		$loginEmail = $this->_request->getParam('email', '');
        $loginPassword = $this->_request->getParam('password', '');
 		$form = new Default_Form_Login();
		$form->setAction('/auth/login');
        $this->view->form = $form;
        if ($this->getRequest()->isPost()) {
            if ($form->isValid($_POST)) {
                $data = $form->getValues();
                $auth = Zend_Auth::getInstance();
                // do the authentication
		        $authAdapter = $this->_getAuthAdapter($loginEmail, $loginPassword);
		        $result = $auth->authenticate($authAdapter);
		        if (!$result->isValid()) {
		            $this->view->errorMessage = 'Invalid email or password. Please try again';
		        } else {
		            // empty password
		            $storage = new Zend_Auth_Storage_Session();
                    $userinfo = $authAdapter->getResultArray($authAdapter->getResultRowObject());
					unset($userinfo['password']);
					$storage->write($userinfo);
                    $this->_redirect('/auth/home');		            
		        }
            }
		}
    }

    public function logoutAction()
    {
        $storage = new Zend_Auth_Storage_Session();
        $storage->clear();
        $this->_redirect('/');
    }

    public function signupAction()
    {
        $user = Doctrine_Core::getTable('Default_Model_User');
		
        $form = new Default_Form_Signup();
		$form->setAction('/auth/signup');
        $this->view->form = $form;
        if ($this->getRequest()->isPost()) {
            if ($form->isValid($_POST)) {
                $data = $form->getValues();
                if ($data['password'] != $data['confirmpassword']) {
                    $this->view->errorMessage = 'Password and confirm password dont \' match';
                    return;
                }
                if ($user->isUnique($data['email'])) {
                    $this->view->errorMessage = 'Name already taken. Please choose another one.';
                    return;
                }
                unset($data['confirmpassword']);
                $user->addUser($data);
                $this->_redirect('/');
            }
		}
    }

    public function forgetAction()
    {
        $form = new Default_Form_Forget;
		$form->setAction('/auth/forgotpass');
		$form->setMethod('POST');
		$this->view->form = $form;
		$loginEmail = $this->_request->getParam('email', '');
		if ($this->getRequest()->isPost()) {
            if ($form->isValid($_POST)) {
                $data = $form->getValues();
				$user = Doctrine_Core::getTable('Default_Model_User');
				/*if email already exist*/
				if($user->isUnique($data['email'])){
					$finduser = $user->findOneBy('email', $data['email']);
					if(isset($finduser->id)){
						$mailer = new Common_Controller_SendMail;
						$mailer->resetpass($data['email'], $finduser);
						$this->view->info=Default_View_Helper_Tr::tr('Please check your Email and folow the link in the email.');	
					}
				}
				else{
						$this->view->errorMessage=Default_View_Helper_Tr::tr('Users with this Email does not exist.');
				}
            }
		}
    }

    public function retrieveAction()
    {
        $code = $this->_request->getParam('uniq');
		if(isset($code)){
			$user_retrieve_model = Doctrine_Core::getTable('Default_Model_UserRetrievePass');
			if($user_retrieve_model->isExistCode($code)){
				$form = new Default_Form_ChangePass;
				$form ->setAction($this->getRequest()->getRequestUri())
					  ->setMethod('POST');
				$this->view->form = $form;
				if ($this->getRequest()->isPost())
				{
					if ($form->isValid($_POST)) {
						$data = $form->getValues();
						if ($data['newpass'] != $data['confirmpassword']) {
		                    $this->view->errorMessage = 'Password and confirm password dont \' match';
		                    return;
		                }
						if($user_retrieve_model->retrievePass($code, $data['newpass'])){
							$this->view->info=Default_View_Helper_Tr::tr('Change password successfull. Please sign in');	
						}
					}
				}	
			}
			else{
				$this->view->info = Default_View_Helper_Tr::tr("Bad retrieve link");
			}
				
		}
		else {
			$this->view->info = Default_View_Helper_Tr::tr("Bad retrieve link");
		}
    }


}











